package com.wyiot.pet.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyiot.pet.mapper.AddressMapper;
import com.wyiot.pet.model.dto.AddressDTO;
import com.wyiot.pet.model.entity.AddressDO;
import com.wyiot.pet.model.vo.AddressVO;
import com.wyiot.core.security.UserContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


/**
 * 地址Service
 *
 * @author yly
 * @since 2022年03月28日
 */
@Service
public class AddressService extends ServiceImpl<AddressMapper, AddressDO> {

    /**
     * 查询id用户拥有的全部地址
     */
    public Page<AddressVO> queryAllAddress(Integer pageNum , Integer pageSize ,Long id) {
        return baseMapper.selectAllAddressByUserId(Page.of(pageNum,pageSize), id);
    }

    /**
     * 跟新该地址为默认地址
     */
    public void isDefault(Long addressId) {

        update(Wrappers.lambdaUpdate(AddressDO.class).eq(AddressDO::getAddressUserId , addressId).set(AddressDO::isAddressIsdefault , false));
        update(Wrappers.lambdaUpdate(AddressDO.class).eq(AddressDO::getAddressId , addressId).set(AddressDO::isAddressIsdefault , true));
    }

    /**
     * 是否默认寄件地址，如果为默认寄件地址保存到数据库
     */
    public void insertDefaultAddress(AddressDTO addressDTO) {
        if (addressDTO.isAddressIsdefault()) {
            AddressDO addressDO = new AddressDO();
            BeanUtils.copyProperties(addressDTO, addressDO);
            addressDO.setAddressUserId(UserContext.getUserId());
            update(Wrappers.lambdaUpdate(AddressDO.class).eq(AddressDO::getAddressUserId ,addressDO.getAddressUserId()).set(AddressDO::isAddressIsdefault ,false));
            save(addressDO);
        }
    }

    /**
     * 查找用户默认地址
     *
     * @param userId 用户id
     */
    public AddressVO queryDefaultAddress(Long userId) {
        return baseMapper.selectAddressIsdefault(userId);
    }
}
